package cn.com.anypay.manager.common.interceptor;

import cn.com.anypay.manager.common.constants.CommonConstants;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * TraceId 拦截器
 * 为每个请求生成或传递 TraceId，用于日志追踪
 */
@Component
public class TraceIdInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 从请求头获取 traceId，如果没有则生成新的
        String traceId = request.getHeader(CommonConstants.TRACE_ID_HEADER);
        if (traceId == null || traceId.trim().isEmpty()) {
            traceId = generateTraceId();
        }

        // 设置到 MDC 中，便于日志输出
        MDC.put("traceId", traceId);

        // 设置到响应头中
        response.setHeader(CommonConstants.TRACE_ID_HEADER, traceId);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                               Object handler, Exception ex) {
        // 清理 MDC
        MDC.remove("traceId");
    }

    /**
     * 生成 TraceId
     */
    private String generateTraceId() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
    }
}